<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useListPage } from "@/composables/useListPage";
import { message } from "@/utils/message";
import brandApi, {
  type BrandListItem,
  type BrandListParams
} from "@/api/system/product/brand";

import Plus from "~icons/ep/plus";
import Refresh from "~icons/ep/refresh";
import EditPen from "~icons/ep/edit-pen";
import Delete from "~icons/ep/delete";

defineOptions({ name: "SystemProductBrand" });

interface BrandFilterForm {
  keyword: string;
  is_visible: string | number;
  owner_org_id: string;
}

interface BrandFormModel {
  id: number | null;
  name: string;
  slug: string;
  logo_url: string;
  banner_url: string;
  description: string;
  content: string;
  origin_country: string;
  owner_org_id: string;
  sort: number;
  is_visible: boolean;
}

const DEFAULT_FILTER: BrandFilterForm = {
  keyword: "",
  is_visible: "",
  owner_org_id: ""
};

const VISIBILITY_OPTIONS = [
  { label: "全部展示状态", value: "" },
  { label: "展示", value: 1 },
  { label: "隐藏", value: 0 }
];

const {
  formState,
  dataList,
  pagination,
  loading,
  onSearch,
  resetForm,
  handlePageChange,
  handleSizeChange
} = useListPage<BrandFilterForm, BrandListItem>(
  {
    fetch: params =>
      brandApi.fetchList(params as BrandListParams & Record<string, any>)
  },
  DEFAULT_FILTER,
  {},
  {
    paramsAdapter: params => {
      const adapted: Record<string, any> = { ...params };
      adapted.is_visible =
        adapted.is_visible === "" ? undefined : Number(adapted.is_visible);
      adapted.owner_org_id = adapted.owner_org_id
        ? Number(adapted.owner_org_id)
        : undefined;
      return adapted;
    },
    responseAdapter: response => ({
      list: response.list ?? [],
      total: response.pagination?.total ?? 0,
      pageSize: response.pagination?.pageSize ?? formState.page_size,
      currentPage: response.pagination?.currentPage ?? formState.page
    })
  }
);

const tableRef = ref();

const columns: TableColumnList = [
  {
    label: "品牌名称",
    prop: "name",
    minWidth: 200,
    align: "left"
  },
  {
    label: "编码",
    prop: "slug",
    minWidth: 160
  },
  {
    label: "发源国家",
    prop: "origin_country",
    minWidth: 140,
    formatter: (row: BrandListItem) => row.origin_country || "-"
  },
  {
    label: "归属组织ID",
    prop: "owner_org_id",
    minWidth: 140,
    formatter: (row: BrandListItem) => row.owner_org_id ?? "-"
  },
  {
    label: "排序",
    prop: "sort",
    width: 90
  },
  {
    label: "展示状态",
    prop: "is_visible",
    width: 120,
    slot: "visible"
  },
  {
    label: "更新时间",
    prop: "update_time",
    width: 180
  },
  {
    label: "操作",
    width: 200,
    fixed: "right",
    slot: "operation"
  }
];

const dialogVisible = ref(false);
const submitting = ref(false);
const formRef = ref<FormInstance>();
const dialogTitle = ref("新增品牌");

const formModel = reactive<BrandFormModel>({
  id: null,
  name: "",
  slug: "",
  logo_url: "",
  banner_url: "",
  description: "",
  content: "",
  origin_country: "",
  owner_org_id: "",
  sort: 0,
  is_visible: true
});

const formRules: FormRules<BrandFormModel> = {
  name: [
    { required: true, message: "请输入品牌名称", trigger: "blur" },
    { min: 1, max: 150, message: "名称长度需在 1-150 字内", trigger: "blur" }
  ],
  slug: [
    { required: true, message: "请输入品牌编码", trigger: "blur" },
    {
      pattern: /^[a-z0-9_-]+$/,
      message: "编码仅支持小写字母、数字、下划线和短横线",
      trigger: "blur"
    }
  ],
  sort: [
    {
      type: "number",
      message: "排序必须为数字",
      trigger: "blur",
      transform: value => Number(value)
    }
  ],
  owner_org_id: [
    {
      validator: (_rule, value, callback) => {
        if (value === null || value === undefined || value === "") {
          callback();
          return;
        }
        if (Number.isNaN(Number(value)) || Number(value) <= 0) {
          callback(new Error("请输入有效的组织ID"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ]
};

const resetFormModel = () => {
  formModel.id = null;
  formModel.name = "";
  formModel.slug = "";
  formModel.logo_url = "";
  formModel.banner_url = "";
  formModel.description = "";
  formModel.content = "";
  formModel.origin_country = "";
  formModel.owner_org_id = "";
  formModel.sort = 0;
  formModel.is_visible = true;
};

const openCreate = () => {
  resetFormModel();
  dialogTitle.value = "新增品牌";
  dialogVisible.value = true;
};

const openEdit = async (id: number) => {
  try {
    const detail = await brandApi.get(id);
    formModel.id = detail.id;
    formModel.name = detail.name;
    formModel.slug = detail.slug;
    formModel.logo_url = detail.logo_url ?? "";
    formModel.banner_url = detail.banner_url ?? "";
    formModel.description = detail.description ?? "";
    formModel.content = detail.content ?? "";
    formModel.origin_country = detail.origin_country ?? "";
    formModel.owner_org_id =
      detail.owner_org_id !== null && detail.owner_org_id !== undefined
        ? String(detail.owner_org_id)
        : "";
    formModel.sort = detail.sort ?? 0;
    formModel.is_visible = detail.is_visible === 1;
    dialogTitle.value = "编辑品牌";
    dialogVisible.value = true;
  } catch (error: any) {
    message(error?.message ?? "获取品牌信息失败", { type: "error" });
  }
};

const handleDelete = async (row: BrandListItem) => {
  try {
    await ElMessageBox.confirm(`确认删除品牌「${row.name}」吗？`, "删除确认", {
      type: "warning",
      confirmButtonText: "删除",
      cancelButtonText: "取消"
    });
  } catch {
    return;
  }

  try {
    await brandApi.remove(row.id);
    message("品牌已删除", { type: "success" });
    await onSearch();
  } catch (error: any) {
    message(error?.message ?? "删除失败", { type: "error" });
  }
};

const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  submitting.value = true;
  const ownerOrgId =
    formModel.owner_org_id === "" || formModel.owner_org_id === undefined
      ? null
      : Number(formModel.owner_org_id);
  const sortValue = Number.isFinite(Number(formModel.sort))
    ? Number(formModel.sort)
    : 0;

  const payload = {
    name: formModel.name,
    slug: formModel.slug,
    logo_url: formModel.logo_url || "",
    banner_url: formModel.banner_url || "",
    description: formModel.description || "",
    content: formModel.content || "",
    origin_country: formModel.origin_country || "",
    owner_org_id:
      ownerOrgId !== null && !Number.isNaN(ownerOrgId) ? ownerOrgId : null,
    sort: sortValue,
    is_visible: formModel.is_visible ? 1 : 0
  };

  try {
    if (formModel.id) {
      await brandApi.update(formModel.id, payload);
      message("品牌已更新", { type: "success" });
    } else {
      await brandApi.create(payload);
      message("品牌已创建", { type: "success" });
    }
    dialogVisible.value = false;
    await onSearch();
  } catch (error: any) {
    message(error?.message ?? "保存失败", { type: "error" });
  } finally {
    submitting.value = false;
  }
};

onMounted(async () => {
  await onSearch();
});
</script>

<template>
  <div class="product-brand-page">
    <el-form
      :inline="true"
      :model="formState"
      class="search-form bg-bg_color w-full pl-4 pt-3 pb-2 overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model.trim="formState.keyword"
          placeholder="品牌名称 / 编码"
          clearable
          class="w-[220px]!"
        />
      </el-form-item>
      <el-form-item label="展示状态" prop="is_visible">
        <el-select
          v-model="formState.is_visible"
          placeholder="全部状态"
          clearable
          class="w-[160px]!"
        >
          <el-option
            v-for="item in VISIBILITY_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="归属组织ID" prop="owner_org_id">
        <el-input
          v-model="formState.owner_org_id"
          placeholder="输入组织ID"
          clearable
          class="w-[180px]!"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title="品牌管理"
      :columns="columns"
      :tableRef="tableRef"
      @refresh="onSearch"
      @fullscreen="tableRef.value?.setAdaptive?.()"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(Plus)"
          @click="openCreate"
        >
          新增品牌
        </el-button>
      </template>
      <template #default="{ size, dynamicColumns }">
        <PureTable
          ref="tableRef"
          v-loading="loading"
          row-key="id"
          :columns="dynamicColumns"
          :data="dataList"
          :size="size"
          :pagination="pagination"
          adaptive
          :adaptiveConfig="{ offsetBottom: 56 }"
          @page-current-change="handlePageChange"
          @page-size-change="handleSizeChange"
        >
          <template #visible="{ row }">
            <el-tag
              :type="row.is_visible === 1 ? 'success' : 'info'"
              size="small"
              effect="plain"
            >
              {{ row.is_visible === 1 ? "展示" : "隐藏" }}
            </el-tag>
          </template>
          <template #operation="{ row }">
            <el-button
              link
              type="primary"
              :icon="useRenderIcon(EditPen)"
              @click="openEdit(row.id)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              :icon="useRenderIcon(Delete)"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </PureTable>
      </template>
    </PureTableBar>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="560px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="formRules"
        label-width="110px"
      >
        <el-form-item label="品牌名称" prop="name">
          <el-input
            v-model.trim="formModel.name"
            placeholder="请输入品牌名称"
          />
        </el-form-item>
        <el-form-item label="品牌编码" prop="slug">
          <el-input v-model.trim="formModel.slug" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="Logo 地址" prop="logo_url">
          <el-input
            v-model="formModel.logo_url"
            placeholder="https://"
            clearable
          />
        </el-form-item>
        <el-form-item label="横幅地址" prop="banner_url">
          <el-input
            v-model="formModel.banner_url"
            placeholder="https://"
            clearable
          />
        </el-form-item>
        <el-form-item label="发源国家" prop="origin_country">
          <el-input
            v-model.trim="formModel.origin_country"
            placeholder="请输入国家/地区"
          />
        </el-form-item>
        <el-form-item label="归属组织ID" prop="owner_org_id">
          <el-input
            v-model="formModel.owner_org_id"
            placeholder="请输入组织ID"
            clearable
            class="w-full"
          />
          <div class="form-tip">可选，如绑定合作供应商组织</div>
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input-number
            v-model="formModel.sort"
            :min="0"
            :max="9999"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="展示状态" prop="is_visible">
          <el-switch
            v-model="formModel.is_visible"
            inline-prompt
            active-text="展示"
            inactive-text="隐藏"
          />
        </el-form-item>
        <el-form-item label="品牌描述" prop="description">
          <el-input
            v-model="formModel.description"
            type="textarea"
            :rows="3"
            placeholder="填写品牌简介（可选）"
          />
        </el-form-item>
        <el-form-item label="详情备注" prop="content">
          <el-input
            v-model="formModel.content"
            type="textarea"
            :rows="4"
            placeholder="可填写备注说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="submitForm">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.product-brand-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-tip {
  margin-left: 12px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}
</style>
